package com.edu.hre.struts.action.survey;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jms.Topic;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.entity.HrePageInfo;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.DynamicConfig;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreJobTitle;
import com.edu.hre.db.pojo.HreSurveyEmpAnswer;
import com.edu.hre.db.pojo.HreSurveyTopic;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.JobTitleForm;
import com.edu.hre.struts.form.dashboard.DashLeaveForm;
import com.edu.hre.struts.form.survey.SurveyManagementListForm;
import com.edu.hre.struts.form.survey.SurveyManagementUpdateForm;

public class SurveyManagementListAction extends Action {
	
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		SurveyManagementListForm beanForm = (SurveyManagementListForm) form; 
		
		beanForm.setCanAdd(userRoleScreen.isCanCreate());
		beanForm.setCanDelete(userRoleScreen.isCanDelete()); 
		String sortBy = RequestUtils.getParameterStr(request, "sort", null);

		if (sortBy != null) { 
			beanForm.setAsc(!beanForm.isAsc());
			CommonUtils.sortCollection(beanForm.getListObjs(), beanForm.isAsc(), sortBy);
			return mapping.findForward("surveyList");
		} else if(request.getParameter(StringConstants.BTN_DELETE) != null){
			passiveDynaCache.removeIfKeyStartWith(RequestUtils.Attribute.TAKE_SURVEY_NOTIFICATION);
			List <SurveyManagementUpdateForm> listObjs = beanForm.getListObjs();
			for(int i = 0; listObjs != null && i < listObjs.size(); i++){
				SurveyManagementUpdateForm tmp = listObjs.get(i);
				if(tmp.getIsSelected()){
					baseService.deleteFirstPojo(tmp.getId(), HreSurveyTopic.class);
				}
			}
		} 
		beanForm.setListUserModified(getListUserCreated());
		List<LabelValueBean> listTmp = CommonUtils.getSubunits();
		beanForm.setListSubunit(listTmp);
		if(beanForm.getSelectedSubunit() == null){
			beanForm.setSelectedSubunit(listTmp.get(0).getValue());
		}
		List<String> columnsList = new ArrayList<String>();
		List<Integer> compareList = new ArrayList<Integer>();
		List<Object> valuesList = new ArrayList<Object>();
		
		if(!"1".equals(beanForm.getSelectedSubunit())){
			columnsList.add("subunitId");
			compareList.add(Compare.EQUAL);
			valuesList.add(Integer.parseInt(beanForm.getSelectedSubunit()));
		} else {
			columnsList.add("subunitId");
			compareList.add(Compare.NOT_EQUAL);
			valuesList.add(-100);
		}
		
		if(!"all".equals(beanForm.getSelectedUser())){
			columnsList.add("userCreated");
			compareList.add(Compare.EQUAL);
			valuesList.add(Integer.parseInt(beanForm.getSelectedUser()));
		}
		String[] columns = new String[columnsList.size()];
		int[] compares = new int[columnsList.size()];
		Object[] values = new Object[columnsList.size()];
		for(int i = 0; i < columnsList.size(); i++){
			columns[i] = columnsList.get(i);
			compares[i] = compareList.get(i);
			values[i] = valuesList.get(i);
		}
		
		int currentPage = RequestUtils.getParameterInt(request, "page", 1);
		int pageSize = CommonUtils.parseInt(DynamicConfig.getConfig(DynamicConfig.PAGE_SIZE), 20);
		
		List<HreUser> listUser = baseService.getPojos(null, -1, null, null, null, 0, 0, HreUser.class);
		List<HreSubunit> listSubunit = baseService.getPojos(null, -1, null, null, null, 0, 0, HreSubunit.class);
		List<HreSurveyTopic> listTopic = baseService.getPojosAnd(columns, compares, values, new String[]{"startDate"}, new Boolean[]{true}, pageSize, pageSize * (currentPage - 1), HreSurveyTopic.class);
		List<SurveyManagementUpdateForm> listObjs = new ArrayList<SurveyManagementUpdateForm>();
		for(int i = 0; listTopic != null && i < listTopic.size(); i++){
			HreSurveyTopic tmp = listTopic.get(i);
			SurveyManagementUpdateForm obj = new SurveyManagementUpdateForm(tmp.getId(), tmp.getName(), tmp.getSubunitId(), 
				getSubunit(listSubunit, tmp.getSubunitId()), tmp.getStartDate(), tmp.getEndDate(),
				tmp.getUserCreated(), getUser(listUser, tmp.getUserCreated()), tmp.getDateCreated(), tmp.getDateModified());
			int countUserTaken = countTakenNumber(tmp.getId());
			obj.setCountUserTaken(countUserTaken);
			if(countUserTaken > 0 || !userRoleScreen.isCanUpdate()){
				obj.setAlowUpdate(false);
			}
			if(tmp.getUserCreated() == user.getId() || tmp.getShowToAll()){
				obj.setAlowAccessByUserCreated(true);
			}
			listObjs.add(obj);
		}
		beanForm.setListObjs(listObjs);
		
		int totalItems = baseService.countByColumns(columns, compares, values, "id", HreSurveyTopic.class);
		List<HrePageInfo> listPages = CommonUtils.getDisplayingPages(currentPage, CommonUtils.getTotalPage(totalItems));
		beanForm.setListPages(listPages);
		beanForm.setTotalItems(totalItems);
		beanForm.setTotalPage(CommonUtils.getTotalPage(totalItems));
		
		return mapping.findForward("surveyList");
	}
	
	private int countTakenNumber(Integer id) {
		String sql = "select count(*) from " + 
					"(select a.user_id, a.topic_id from hre_survey_emp_answer a " +  
					"group by a.user_id, a.topic_id having a.topic_id = ?) tmp";
		List<Object[]> listObj = baseService.listArrayObject(sql, 0, 0, id);
		if(listObj == null || listObj.size() == 0){
			return 0;
		}
		return ((BigInteger)listObj.get(0)[1]).intValue();
	}

	public static String getUser(List<HreUser> listObjs, int id){
		for(int i = 0; listObjs != null && i < listObjs.size(); i++){
			if(id == listObjs.get(i).getId()){
				return listObjs.get(i).getUserName();
			}
		}
		return "Unknown";
	}
	
	public static String getSubunit(List<HreSubunit> listObjs, int id){
		for(int i = 0; listObjs != null && i < listObjs.size(); i++){
			if(id == listObjs.get(i).getId()){
				return listObjs.get(i).getName();
			}
		}
		return "Unknown";
	}
	
	public static List<LabelValueBean> getListUserCreated(){
		List<LabelValueBean> listValueBean = new ArrayList<LabelValueBean>();
		listValueBean.add(new LabelValueBean("-- All --", "all"));
		String sql = "select u.id, u.user_name " +  
						"from hre_survey_topic t  " + 
						"inner join hre_user u  " + 
						"on t.user_created = u.id " + 
						"group by u.id, u.user_name ";
		List<Object[]> listObjs = baseService.listArrayObject(sql, 0, 0);
		for(int i = 0; listObjs != null && i < listObjs.size(); i++){
			Object[] o = listObjs.get(i);
			String value = ((Integer) o[1]) + "";
			String label = (String) o[2];
			LabelValueBean bean = new LabelValueBean(label, value);
			listValueBean.add(bean);
		}
		return listValueBean;
	}
}

//--------------------------------------------------------------------------------------
//SELECT t.id, t.name, s.name, s.id, t.start_date, t.end_date, 
//u.user_name, u.id, t.date_created, t.date_modified, t.show_to_all, count(a.id)
//FROM hrentry_db.hre_survey_topic t 
//left outer join hre_survey_emp_answer a on a.topic_id = t.id
//left outer join hre_subunit s on s.id = t.subunit_id
//left outer join hre_user u on u.id = t.user_created
//group by t.id, t.name, s.name, s.id, t.start_date, t.end_date, 
//u.user_name, u.id, t.date_created, t.date_modified, t.show_to_all
//having (u.id = 20 or t.show_to_all = true)
//order by t.start_date desc

